package logic

import (
	"context"
	"errors"
	"novel-mgr1/cache"
	"novel-mgr1/model"
	"novel-mgr1/pkg"

	"novel-mgr1/userrpc/internal/svc"
	"novel-mgr1/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码
func (l *UpdatePasswordLogic) UpdatePassword(in *userrpc.UpdatePasswordRequest) (*userrpc.UpdatePasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	err := user.FindUserByMobile(model.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("未注册")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sms"+in.Mobile).Result()
	if result == "" {
		return nil, errors.New("请发送验证码")
	}
	if result != in.SandSmsCode {
		return nil, errors.New("验证码错误")
	}
	if user.Password == pkg.Str(in.NewPassword) {
		return nil, errors.New("不能与原密码相同")
	}
	if in.NewPassword != in.AgainNewPassword {
		return nil, errors.New("与新密码密码不相同")
	}
	user.Password = pkg.Str(in.AgainNewPassword)

	if err = user.UpdatePassword(model.DB); err != nil {
		return nil, errors.New("修改失败")
	}
	return &userrpc.UpdatePasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
